<template>
  <view class="content">
    <view class="upload-wrapper">
      <!-- 上传按钮固定在左侧 -->
      <view class="upload-btn-container">
        <up-button :customStyle="{ width: '200rpx', borderRadius: '8rpx',  }" type="primary" text="选择审批单" @click="openPopup"></up-button>
      </view>

      <view class="file-list-container">
        <view class="file-item" v-for="(item,index) in checkData" :key="index" >
          <text class="file-name" @click="TrouterPUsh(item)">{{ truncateMiddle(item.title )}}</text>
          <view class="status" :class="getStatusClass(item.status)">
            {{ getStatusText(item.status) }}
          </view>
          <text class="delete-btn" @click="removeItem(index)">删除</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { useUserStore } from '@/pinia-store/user'
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js"
import { mapStores } from 'pinia'
import componentMinxins from '../ComponentMinxins'

export default {
  mixins: [componentMinxins, MescrollMixin],
  props: {
    itemIndex: {
      type: Number,
      default: 0
    },
    doc: {
      type: Array,
      default: []
    },
    value: {
      type: String,
      default: null
    },
    placeholder: {
      type: String,
      default: '请输入内容'
    },
    options: {
      type: Array,
      default: () => {
        return []
      }
    },
    source: {
      type: Number,
      default: 1
    },
    sourceType: {
      type: Number,
      default: 1
    },
    format: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    },
    field: {
      type: [String, Number],
      required: true
    },
    itemId: {
      type: String,
      required: true
    },
    ApplyDetailList: {
      type: Array,
      default: () => {
        return []
      }
    },
  },
  data() {
    return {
      show: false,
      titlesp: '审批单列表',
      tabs: [{
        name: "我审批的"
      }, {
        name: "我发起的"
      }, {
        name: "我收到的"
      }],
      upOption: {
        page: {
          size: 10 // 每页数据的数量,默认10
        },
        noMoreSize: 10, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
        empty: {
          tip: '暂无更多...'
        }
      },
      total: 0,
      queryParams: {
        pageSize: 3,
        pageNum: 1
      },
      list: [],
      keywords: '', //搜索关键字
      type: '', //搜索下拉框
      currentIndex: 0,
      aloneChecked: [],
      checkData: [],
      loading: false,
      noMore: false,
      isRefreshing: false,
      listHeight: 0, // 动态计算的高度
      listHeightStyle: {}, // 动态计算的样式
      topHeight: 0,
      listHeightStylePage: {},
    }
  },
  onReady() {

  },
  computed: {
    ...mapStores(useUserStore)
  },
  created() {
    uni.$on('AssociationTableList',(data)=>{
      if (data.itemId === this.itemId) {
        this.checkData = data.data;
      }
    })
    // #ifdef H5
    this.listHeightStylePage = {
      height: `${window.innerHeight}px`,
    };
    // #endif

    // #ifdef APP-PLUS
    this.listHeightStylePage = {
      height: `100vh`,
    };
    // #endif
    let app = uni.getSystemInfoSync();
    this.topHeight = app.statusBarHeight;
  },
  mounted() {
    let value = uni.getStorageSync('formData');
    let formItems = JSON.parse(value.formItems);
    formItems.forEach(item => {
      if (item.title == this.title) {
        uni.removeStorageSync(`${item.id}`);
      }
    })
    this.calculateListHeight()
    this.setechodata()
  },
  watch: {
    checkData: {
      handler(newValue) {
        let value = uni.getStorageSync('formData');
        let formItems = JSON.parse(value.formItems);
        formItems.forEach(item => {
          if (item.title == this.title) {
            uni.removeStorageSync(item.id);
            let filteredData = newValue.map(data => ({
              id: data.id,
              title: data.title
            }));
            item.value = newValue[0];
            uni.setStorageSync(item.id, filteredData);
          }
        })
      },
      deep: true
    }
  },
  methods: {
    setechodata(){
        // 添加数据回显逻辑
      if (this.ApplyDetailList && this.ApplyDetailList.formData  && this.itemId)  {
          // 检查 formData 中是否存在当前 itemId 对应的字段 
          if (this.ApplyDetailList.formData.hasOwnProperty(this.itemId))  {
            // 获取对应的值
            const fieldValue = this.ApplyDetailList.formData[this.itemId]; 
            
            // 如果值是数组，取第一个元素（根据你的数据结构）
            if (Array.isArray(fieldValue)  && fieldValue.length  > 0) {
              this.checkData = fieldValue || ''
            } else {
              // 直接赋值 
              this.checkData = fieldValue || '';
            }
          }
        }
    },
    truncateMiddle(text, maxLength = 20) {
      if (text.length <= maxLength) return text;
      const half = Math.floor(maxLength / 2.5);
      return `${text.slice(0, half)}...${text.slice(-half)}`;
    },
    // 获取状态样式类
    getStatusClass(status) {
      return `status-${status}`;
    },
    getStatusText(status) {
      const statusMap = {
        1: '审批中',
        2: '审批同意',
        3: '审批驳回',
        4: '审批撤销',
      };
      return statusMap[status] || '';
    },
    // 去处理
    TrouterPUsh (item) {
        uni.navigateTo({
          url: '/pages/apply/oaList/applyOrderDetail?id=' + item.id
        });
    },
    removeItem(index) {
      uni.showModal({
        title: '提示',
        content: '确定要移除该审批单吗？',
        success: (res) => {
          if (res.confirm) {
            this.checkData.splice(index, 1);
          }
        }
      });
    },
    calculateListHeight() {
      const windowHeight = window.innerHeight; // 视口高度
      const topHeight = this.topHeight || 0; // 顶部安全高度
      const navbarHeight = 44; // 导航栏高度（假设为 44px）
      const tabsHeight = 88;
      // #ifdef APP-PLUS
      this.listHeightStyle = {
        overflowY: 'hidden'
      };
      // #endif

      // #ifdef H5
      const listHeight = windowHeight - topHeight - navbarHeight - tabsHeight;
      this.listHeightStyle = {
        height: `${listHeight}px`,
        overflowY: 'hidden'
      };
      // #endif
    },

    openPopup() {
     let checkData = uni.getStorageSync(this.itemId) || [];

      uni.navigateTo({
        url: `/pages/apply/form/components/AssociationTableList?type=${this.type}&doc=${JSON.stringify(this.doc)}&checkData=${JSON.stringify(checkData)}&itemId=${this.itemId}`
      });
    },
    rightClick() {
      this.show = false;
    },
    search() {

    },

  }
}
</script>

<style scoped>
.content {
  padding: 5rpx;
}
/* 审批状态 */
.status {
  margin-left: 10rpx;
  font-size: 28rpx;
  font-weight: bold;
}


.status-1 {
  color: #3c9cff;
}

.status-2 {
  color: #5ac725;
}

.status-3 {
  color: #f56c6c;
}

.status-4 {
  color: #909399;
}
.upload-wrapper {
  display: flex;
  flex-direction: column;
}

.upload-btn-container {
  width: 200rpx;
  margin-bottom: 10rpx;
}

.file-list-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
}

.file-name {
  flex: 1;
  color: #333;
  font-size: 28rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.delete-btn {
  color: #fff;
  background-color: #f56c6c;
  padding: 8rpx 20rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
  margin-left: 20rpx;
}
</style>




